package com.tongda.menu.activity;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import com.tongda.core.common.Constants;
import com.tongda.core.common.KernalApplication;
import com.tongda.core.service.BaseService;
import com.tongda.core.utils.ActivityUtil;
import com.tongda.core.utils.SharedPreferencesUtils;
import com.tongda.menu.R;
import com.tongda.menu.util.ActivityMenuUtil;
import com.tongda.menu.util.UpdateVersionHelper;
import android.content.pm.ActivityInfo;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;


public class SettingActivity extends PreferenceActivity{
	
	
	String oldIp;
	String oldPort;
	String oldPicturesPort;
	private CheckBoxPreference cloudservice;
	private EditTextPreference localservice;
	private String localStr;
	private CheckBoxPreference testService;
	private CheckBoxPreference isRemember;
	private KernalApplication application;
	private String currentUser;
	private boolean isRemUser;
	
    final Handler handler = new Handler(){

		@Override
    	public void handleMessage(Message msg) {
    		super.handleMessage(msg);
    		Bundle bundle = msg.getData();
    		int from = bundle.getInt("from");
    		boolean isServerOk = bundle.getBoolean("isServerOk");
    		String newValue = bundle.getString("newValue", "");
    		if(from==0){
        		if(isServerOk){
        			Toast.makeText(SettingActivity.this, "服务器IP可用", Toast.LENGTH_SHORT).show();
    				Constants.resetServerIp( newValue);
    				localservice.setSummary(newValue);
    				SharedPreferencesUtils.setParam(SettingActivity.this, "server_ip", newValue);
    				SharedPreferencesUtils.setParam(SettingActivity.this, Constants.MENU_IS_REM_CURRENTUSER, false);
    				SharedPreferencesUtils.setParam(SettingActivity.this, Constants.USERNAME, BaseActivity.SUPER_USER_NAME);
    				SharedPreferencesUtils.setParam(SettingActivity.this, Constants.PASSWORD, BaseActivity.SUPER_USER_PASSWORD);
    		        ActivityMenuUtil.restartApp(SettingActivity.this);
        		}else{
        			Toast.makeText(SettingActivity.this, "服务器IP不可用", Toast.LENGTH_SHORT).show();
        		}
    		}else{
        		if(isServerOk){
        			Toast.makeText(SettingActivity.this, "服务器IP可用", Toast.LENGTH_SHORT).show();
   				    ActivityMenuUtil.restartApp(SettingActivity.this);
        		}else{
        			Toast.makeText(SettingActivity.this, "服务器IP不可用", Toast.LENGTH_SHORT).show();
        		}
    		}
    		
    	}
    };
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.preference);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		application = KernalApplication.getInstance();
		isRemUser = (Boolean) SharedPreferencesUtils.getParam(SettingActivity.this, Constants.MENU_IS_REM_CURRENTUSER, false);
		currentUser = (String) SharedPreferencesUtils.getParam(SettingActivity.this, Constants.USERNAME, "");
		TextView versionNameTv = (TextView)findViewById(R.id.setting_versioname);
		versionNameTv.setText("当前版本："+UpdateVersionHelper.getVersionName(this)+"(点击检查最新版本)");
		
		
		// 从资源文件中获取Preferences ，选择的值将会自动保存到SharePreferences
		addPreferencesFromResource(R.xml.system_settings);
		
		oldIp = "".equals(PreferenceManager.getDefaultSharedPreferences(this).getString("server_ip", "")) ? Constants.SERVER_IP : PreferenceManager.getDefaultSharedPreferences(this).getString("server_ip", "");
		oldPort = "".equals(PreferenceManager.getDefaultSharedPreferences(this).getString("server_port", "")) ? Constants.SERVER_PORT : PreferenceManager.getDefaultSharedPreferences(this).getString("server_port", "");
		oldPicturesPort = "".equals(PreferenceManager.getDefaultSharedPreferences(this).getString("pictures_server_port", "")) ? Constants.PICTURES_SERVER_PORT : PreferenceManager.getDefaultSharedPreferences(this).getString("pictures_server_port", "");

		localservice = (EditTextPreference)findPreference("localservice");
		localStr = "".equals(PreferenceManager.getDefaultSharedPreferences(this).getString("server_ip", "")) ? Constants.SERVER_IP : PreferenceManager.getDefaultSharedPreferences(this).getString("server_ip", "");
		localservice.setSummary(localStr);
		localservice.setText(localStr);
		localservice.setPositiveButtonText("确定");
		localservice.setNegativeButtonText("取消");
		
		localservice.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference arg0, final Object newValue) {
	            
	            Thread isokThread = new Thread(new Runnable() {
					
					@Override
					public void run() {
						//发布的时候放开
						Constants.resetServerPort("8668");
						Message msg = handler.obtainMessage();
						boolean isServerOk = SplashActivity.isServerOk(newValue+"");
						Bundle data = new Bundle();
						data.putInt("from", 0);
						data.putString("newValue", newValue+"");
						data.putBoolean("isServerOk", isServerOk);
						msg.setData(data );
						handler.sendMessage(msg);
					}
				});
	            isokThread.start();
	            
				return true;
			}
		});
		
		//云服务模块以后再操作
		cloudservice = (CheckBoxPreference)findPreference("cloudservice");
		cloudservice.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			
			@Override
			public boolean onPreferenceChange(Preference preference, Object newValue) {
				if("true".equals("" + newValue)){
				}else if("false".equals("" + newValue)){
				}
				return true;
			}
		});
		
		//体验模式
		testService = (CheckBoxPreference)findPreference("testservice");
		testService.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			
			@Override
			public boolean onPreferenceChange(Preference preference, Object newValue) {
				if("true".equals(""+newValue)){
					Constants.resetServerIp("www.mixi8.cn");
					Constants.resetServerPort("8888");
					
		            final Handler handler = new Handler(){

						@Override
		            	public void handleMessage(Message msg) {
		            		super.handleMessage(msg);
		            		boolean isServerOk = msg.getData().getBoolean("isServerOk");
		            		if(isServerOk){
		            			Toast.makeText(SettingActivity.this, "服务器IP可用", Toast.LENGTH_SHORT).show();
		            			SharedPreferencesUtils.setParam(SettingActivity.this, "server_ip", "www.mixi8.cn");
	        				    ActivityMenuUtil.restartApp(SettingActivity.this);
		            		}else{
		            			Toast.makeText(SettingActivity.this, "服务器IP不可用", Toast.LENGTH_SHORT).show();
		            		}
		            		
		            	}
		            };
		            
					Thread subThread = new Thread(new Runnable() {
						
						@Override
						public void run() {
							Message msg = handler.obtainMessage();
							boolean isServerOk = SplashActivity.isServerOk("www.mixi8.cn");
							Bundle data = new Bundle();
							data.putBoolean("isServerOk", isServerOk);
							msg.setData(data );
							handler.sendMessage(msg);
						}
					});
					subThread.start();
				}else if("false".equals(""+newValue)){
					
				}
				return true;
			}
		});
		
		isRemember = (CheckBoxPreference)findPreference("isRemember");
		isRemember.setChecked(isRemUser);
		if(currentUser.equals("")){
			isRemember.setEnabled(false);
		}else{
			isRemember.setEnabled(true);
		}
		isRemember.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			
			@Override
			public boolean onPreferenceChange(Preference preference, Object newValue) {
				if("true".equals(newValue+"")){
					SharedPreferencesUtils.setParam(SettingActivity.this, Constants.MENU_IS_REM_CURRENTUSER, true);
					Toast.makeText(SettingActivity.this, "记住登录状态,后续操作不用验证账号", Toast.LENGTH_SHORT).show();
				}else{
					SharedPreferencesUtils.setParam(SettingActivity.this,Constants.MENU_IS_REM_CURRENTUSER, false);
					Toast.makeText(SettingActivity.this, "取消记住登录状态,后续操作验证账号", Toast.LENGTH_SHORT).show();
				}
				return true;
			}
		});
		
		findViewById(R.id.setting_close).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v){
				SettingActivity.this.finish();
			}
		});

		versionNameTv.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				UpdateVersionHelper update = new UpdateVersionHelper(SettingActivity.this);
				update.startProcess();
			}
		});
		
		findViewById(R.id.setting_closeBtn).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				SettingActivity.this.finish();
			}
		});
		
		final TextView userTv = (TextView)findViewById(R.id.setting_currentUser);
		userTv.setText("当前登录账号："+currentUser);
		
		TextView quitTv = (TextView)findViewById(R.id.setting_quit);
		quitTv.setText(Html.fromHtml("<font color='blue' >"+"退出登录"+"</font>"));
		quitTv.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
		quitTv.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				SharedPreferencesUtils.setParam(SettingActivity.this, Constants.USERNAME, "");
				SharedPreferencesUtils.setParam(SettingActivity.this, Constants.PASSWORD, "");
				SharedPreferencesUtils.setParam(SettingActivity.this, Constants.MENU_IS_REM_CURRENTUSER, false);
				isRemember.setChecked(false);
				isRemember.setEnabled(false);
				userTv.setText("当前登录账号：   ");
				
			}
		});
		
		 TextView updateTv = (TextView)findViewById(R.id.setting_updateDish);
		 updateTv.setText(Html.fromHtml("<font color='blue' >"+"更新菜谱"+"</font>"));
		 updateTv.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
		 updateTv.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
	            Thread isokThread = new Thread(new Runnable() {
					
					@Override
					public void run() {
						//发布的时候放开此端口
						Constants.resetServerPort("8668");
						Message msg = handler.obtainMessage();
						boolean isServerOk = SplashActivity.isServerOk("".equals(PreferenceManager.getDefaultSharedPreferences(SettingActivity.this).getString("server_ip", "")) ? Constants.SERVER_IP : PreferenceManager.getDefaultSharedPreferences(SettingActivity.this).getString("server_ip", ""));
						Bundle data = new Bundle();
						data.putInt("from", 1);
						data.putBoolean("isServerOk", isServerOk);
						msg.setData(data );
						handler.sendMessage(msg);
					}
				});
	            isokThread.start();
			}
		});
	}
	
}
